//
//  PersonalVC.m
//  BagsProject
//
//  Created by sunsoft on 2017/3/16.
//  Copyright © 2017年 sunnsoft. All rights reserved.
//

#import "PersonalVC.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "ChangeNameVC.h"

@interface PersonalVC ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>

@property (nonatomic,strong) UITableView * PTableView;
@property (nonatomic,strong) UIView * accessoryView;
@property (nonatomic, strong) UIImageView *iconView;
@property (nonatomic,strong) UITextView * changeNameTV;
@property (nonatomic,strong) NSBundle *bundle;
@property (nonatomic, copy) NSString *changedName;
@property (nonatomic, copy) NSString *HeadPath;
@end

@implementation PersonalVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [SEChangeLanguage initUserLanguage];
    _bundle = [SEChangeLanguage bundle];
    self.view.backgroundColor = [UIColor whiteColor];
    __weak typeof(self) weakSelf = self;
    
    [HNaviBar customNaviBarWithTitle:[_bundle localizedStringForKey:@"個人資料" value:nil table:@"Localization"] andLeftEvent:^(UIButton *leftSender) {
        NSDictionary *params;
//        _HeadPath
        [SVProgressHUD show];
        if (_HeadPath == nil && _changedName != nil) {
            
            params = @{@"id": [SEUserData sharedInstance].user.ID ?: @"",
                       @"language": [SEUserData sharedInstance].user.languageStr ?: @"",
                       @"nickName": _changedName ?: @"",
                       @"logoPath": [SEUserData sharedInstance].user.logoPath ?: @""
                       };

        }else if(_changedName == nil && _HeadPath != nil ){
            
            params = @{@"id": [SEUserData sharedInstance].user.ID ?: @"",
                       @"language": [SEUserData sharedInstance].user.languageStr ?: @"",
                       @"nickName": [SEUserData sharedInstance].user.nickName ?: @"",
                       @"logoPath": _HeadPath ?: @""
                       };
        }else if (_changedName != nil && _HeadPath != nil ){
            
            params = @{@"id": [SEUserData sharedInstance].user.ID ?: @"",
                       @"language": [SEUserData sharedInstance].user.languageStr ?: @"",
                       @"nickName": _changedName ?: @"",
                       @"logoPath": _HeadPath ?: @""
                       };
        }else{
            
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [SVProgressHUD dismiss];
            return ;
        }
        HLog(@"%@",params);
        [[SENetWorkTool sharedTool] requestPOST:@"/user/saveInfo.aspf" params:params callback:^(id response, NSError *error) {
            
            if (error != nil || [response[SEStatusKey] integerValue] != 10001) {
                [SVProgressHUD showErrorWithStatus:[response valueForKey:SEMSGKey] ?: [_bundle localizedStringForKey:SENetworkError value:nil table:@"Localization"]];
                return;
            }
            }];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showSuccessWithStatus:[_bundle localizedStringForKey:@"修改成功" value:nil table:@"Localization"]];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            
        });
    } aimView:self.view];
    
    [self initTableView];
    
    
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self removeNotifacation];
}
#pragma mark - keyboard



/// 修改昵称
- (void)sureChangeName {
    if ([self.changeNameTV.text isEqualToString:@""]) {
        
        self.changedName = [SEUserData sharedInstance].user.nickName;
    }else self.changedName = self.changeNameTV.text;
    
    [self.PTableView reloadData];
    [self.changeNameTV resignFirstResponder];
}

-(void)initTableView{
    
    self.PTableView.delegate = self;
    self.PTableView.dataSource = self;
    self.PTableView.backgroundColor = GrayColor;
    [self.PTableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    [self.view addSubview:self.PTableView];
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:{
            TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
            imagePicker.allowPickingVideo = NO;
            [imagePicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                
                UIImage *image = photos.firstObject;
                NSData *imageData = [SEGeneralTool reSizeImageData:image maxImageSize:800 maxSizeWithKB:1024];
                [SVProgressHUD show];
                
                NSDictionary *params = @{
                                         @"fileType": @"1"
                                         };
                [[SENetWorkTool sharedTool] uploadImage:imageData urlString:@"/fileUploadByByte.aspf" name:@"photoData" params:params callback:^(id response, NSError *error) {
                    
                    HLog(@"%@",response);
                    if (error || [[response valueForKey:SEStatusKey] integerValue] != 10001) {
                        
                        [SVProgressHUD showErrorWithStatus:[response valueForKey:SEMSGKey] ?: [_bundle localizedStringForKey:SENetworkError value:nil table:@"Localization"]];
                        [SVProgressHUD dismiss];
                        return;
                    }
                    
                    self.iconView.image = image;
                    NSDictionary * path = response[@"dataInfo"];
                    _HeadPath = path[@"path"];
                    [SVProgressHUD dismiss];
                }];

                
            }];
            
            [self presentViewController:imagePicker animated:YES completion:nil];
            
        }
        break;
        
        default:
            
            if (indexPath.row == 0) {
                ChangeNameVC * cvc = [ChangeNameVC new];
                [cvc setInfoBlock:^(NSString *name) {
                    _changedName = name;
                    [self.PTableView reloadData];
                }];
                [self.navigationController pushViewController:cvc animated:YES];
            }
        break;
    }

}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    switch (section) {
        case 0:
            return 1;
            break;
        default:
            return 2;
            break;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    
    cell.detailTextLabel.font = HHFont(13);
    cell.detailTextLabel.textColor = LabelColor;
    cell.textLabel.font = HHFont(15);
    cell.textLabel.textColor = LabelColor;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    switch (indexPath.section) {
        case 0:
            cell.accessoryView = self.accessoryView;
            cell.textLabel.text = [_bundle localizedStringForKey:@"相片" value:nil table:@"Localization"];
            break;
        default:
            if (indexPath.row == 0) {
                cell.textLabel.text = [_bundle localizedStringForKey:@"用戶名稱" value:nil table:@"Localization"];
                if (self.changedName == nil) {
                    cell.detailTextLabel.text = [SEUserData sharedInstance].user.nickName;
                }else cell.detailTextLabel.text = self.changedName;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }else{
                
                cell.textLabel.text = [_bundle localizedStringForKey:@"電話" value:nil table:@"Localization"];
                cell.detailTextLabel.text = cell.detailTextLabel.text = [SEUserData sharedInstance].user.userName;
            }
            
            break;
    }

    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            return 80;
            break;
            
        default:
            
            return 44;
            break;
    }
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section{
    
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView * bgiew = [[UIView alloc] initWithFrame:CGRectMake(0, 0, HHScreenWidth, 10)];
    bgiew.backgroundColor = GrayColor;
    return bgiew;
}
- (void)removeNotifacation
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark - Setter & Getter

- (UIView *)accessoryView {
    if (_accessoryView == nil) {
        _accessoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 55, 55)];
        _iconView = [[UIImageView alloc] initWithFrame:_accessoryView.frame];
        _iconView.contentMode = UIViewContentModeScaleAspectFill;
        [_iconView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SEURL,[SEUserData sharedInstance].user.logoPath]] placeholderImage:HeadImage];
        _iconView.layer.cornerRadius = 28;
        _iconView.layer.masksToBounds = YES;
        [_accessoryView addSubview:_iconView];
        
    }
    
    return _accessoryView;
}

-(UITableView *)PTableView{
    
    if (_PTableView == nil) {
        _PTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, HHScreenWidth, HHScreenHeight-64) style:UITableViewStylePlain];
        
    }
    return _PTableView;
}
-(void)viewWillDisappear:(BOOL)animated{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
